package org.jeecg.modules.demo.category_manage.controller;

import java.io.*;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.config.shiro.IgnoreAuth;
import org.jeecg.modules.demo.category_manage.entity.CategoryManage;
import org.jeecg.modules.demo.category_manage.service.ICategoryManageService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 类目管理
 * @Author: jeecg-boot
 * @Date:   2024-11-02
 * @Version: V1.0
 */
@Api(tags="类目管理")
@RestController
@RequestMapping("/category_manage/categoryManage")
@Slf4j
public class CategoryManageController extends JeecgController<CategoryManage, ICategoryManageService> {
	@Autowired
	private ICategoryManageService categoryManageService;
	
	/**
	 * 分页列表查询
	 *
	 * @param categoryManage
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "类目管理-分页列表查询")
	@ApiOperation(value="类目管理-分页列表查询", notes="类目管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CategoryManage>> queryPageList(CategoryManage categoryManage,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        QueryWrapper<CategoryManage> queryWrapper = QueryGenerator.initQueryWrapper(categoryManage, req.getParameterMap());
		Page<CategoryManage> page = new Page<CategoryManage>(pageNo, pageSize);
		IPage<CategoryManage> pageList = categoryManageService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param categoryManage
	 * @return
	 */
	@AutoLog(value = "类目管理-添加")
	@ApiOperation(value="类目管理-添加", notes="类目管理-添加")
	@RequiresPermissions("category_manage:category_manage:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CategoryManage categoryManage) {
		categoryManageService.save(categoryManage);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param categoryManage
	 * @return
	 */
	@AutoLog(value = "类目管理-编辑")
	@ApiOperation(value="类目管理-编辑", notes="类目管理-编辑")
	@RequiresPermissions("category_manage:category_manage:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CategoryManage categoryManage) {
		categoryManageService.updateById(categoryManage);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "类目管理-通过id删除")
	@ApiOperation(value="类目管理-通过id删除", notes="类目管理-通过id删除")
	@RequiresPermissions("category_manage:category_manage:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		categoryManageService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "类目管理-批量删除")
	@ApiOperation(value="类目管理-批量删除", notes="类目管理-批量删除")
	@RequiresPermissions("category_manage:category_manage:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.categoryManageService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "类目管理-通过id查询")
	@ApiOperation(value="类目管理-通过id查询", notes="类目管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CategoryManage> queryById(@RequestParam(name="id",required=true) String id) {
		CategoryManage categoryManage = categoryManageService.getById(id);
		if(categoryManage==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(categoryManage);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param categoryManage
    */
    @RequiresPermissions("category_manage:category_manage:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CategoryManage categoryManage) {
        return super.exportXls(request, categoryManage, CategoryManage.class, "类目管理");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("category_manage:category_manage:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CategoryManage.class);
    }
	 @GetMapping("/run-script")
	 public String runPythonScript(@RequestParam(name="store",required = true) String store) {
		 StringBuilder output = new StringBuilder();
		 System.out.println("Received store: " + store);
		 try {
			 ProcessBuilder processBuilder = new ProcessBuilder("python", "/home/rpa_test/start.py",store);
			 processBuilder.redirectErrorStream(true); // 合并错误流和输出流
			 Process process = processBuilder.start();

			 // 读取输出
			 try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
				 String line;
				 while ((line = reader.readLine()) != null) {
					 output.append(line).append("\n");
				 }
			 }

			 // 等待脚本执行完成
			 int exitCode = process.waitFor();
			 output.append("Script executed with exit code: ").append(exitCode);

			 if (exitCode != 0) {
				 return "Script execution failed with exit code: " + exitCode;
			 }

		 } catch (IOException e) {
			 log.error("IOException while running Python script", e);
			 return "IOException: " + e.getMessage();
		 } catch (InterruptedException e) {
			 log.error("InterruptedException while running Python script", e);
			 return "InterruptedException: " + e.getMessage();
		 }

		 return output.toString();
	 }
	 /**
	  * 下载导入模板
	  *
	  * @param response
	  * @return
	  */
	 @ApiOperation(value = "类目管理-下载导入模板", notes = "类目管理-下载导入模板")
	 @IgnoreAuth
	 @GetMapping(value = "/downloadTemplate")
	 public ModelAndView downloadTemplate(HttpServletResponse response) {
		 // 设置导出参数
		 ExportParams exportParams = new ExportParams("类目管理导入模板", "模板");

		 // 创建一个空的列表，因为我们只需要字段名作为模板
		 List<CategoryManage> list = Arrays.asList();

		 // 返回Excel视图
		 return new ModelAndView(new JeecgEntityExcelView(), NormalExcelConstants.FILE_NAME, "类目管理导入模板")
				 .addObject(NormalExcelConstants.CLASS, CategoryManage.class)
				 .addObject(NormalExcelConstants.PARAMS, exportParams)
				 .addObject(NormalExcelConstants.DATA_LIST, list);
	 }
	 @IgnoreAuth
	 @GetMapping("/run-script1")
	 public String runPythonScript1(@RequestParam String[] id, @RequestParam String[] stores) {
		 StringBuilder output = new StringBuilder();

		 // 打印接收到的参数
		 System.out.println("Received stores: " + String.join(", ", stores));
		 System.out.println("Received ids: " + String.join(", ", id));

		 try {
			 // 构建命令
			 ProcessBuilder processBuilder = new ProcessBuilder("python3.10", "/home/rpa_test/start.py");

			 // 添加参数
			 List<String> command = new ArrayList<>();
			 command.add("python3.10");
			 command.add("/home/rpa_test/start.py");

			 // 将 id 和 stores 参数添加到命令中
			 for (String s : id) {
				 command.add(s);
			 }
			 for (String s : stores) {
				 command.add(s);
			 }

			 processBuilder.command(command);
			 processBuilder.redirectErrorStream(true); // 合并错误流和输出流
			 Process process = processBuilder.start();

			 // 读取输出
			 try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
				 String line;
				 while ((line = reader.readLine()) != null) {
					 output.append(line).append("\n");
				 }
			 }

			 // 等待脚本执行完成
			 int exitCode = process.waitFor();
			 output.append("Script executed with exit code: ").append(exitCode);

			 if (exitCode != 0) {
				 return "Script execution failed with exit code: " + exitCode;
			 }

		 } catch (IOException e) {
			 System.err.println("IOException while running Python script: " + e.getMessage());
			 return "IOException: " + e.getMessage();
		 } catch (InterruptedException e) {
			 System.err.println("InterruptedException while running Python script: " + e.getMessage());
			 return "InterruptedException: " + e.getMessage();
		 }

		 return output.toString();
	 }



 }
